//
//  JGDistrictViewController.m
//  JGMeiTuanHD
//
//  Created by JJetGu on 15/9/10.
//  Copyright (c) 2015年 Free. All rights reserved.
//

#import "JGRegionViewController.h"
#import "JGHomeDropdown.h"
#import "UIView+Extension.h"
#import "JGCityViewController.h"
#import "JGNavigationController.h"
#import "JGRegion.h"
#import "JGConst.h"

@interface JGRegionViewController () <JGHomeDropdownDataSource, JGHomeDropdownDelegate>

- (IBAction)changeCity:(id)sender;

@end

@implementation JGRegionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建下拉菜单
    UIView *title = [self.view.subviews firstObject];
    JGHomeDropdown *dropdown = [JGHomeDropdown dropdown];
    dropdown.y = title.height;
    dropdown.dataSource = self;
    dropdown.delegate = self;
    [self.view addSubview:dropdown];
    
    // 设置控制器在popover中的尺寸
    self.preferredContentSize = CGSizeMake(dropdown.width, CGRectGetMaxY(dropdown.frame));
}

- (IBAction)changeCity:(id)sender {
    
    [self.popover dismissPopoverAnimated:YES];
    
    JGCityViewController *city = [[JGCityViewController alloc] init];
    JGNavigationController *nav = [[JGNavigationController alloc] initWithRootViewController:city];
    nav.modalPresentationStyle = UIModalPresentationFormSheet;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:nil];
    
    // self.presentedViewController会引用着被modal出来的控制器
    // modal出来的是MTNavigationController
    // dismiss掉的应该也是MTNavigationController
    
}

#pragma mark - JGHomeDropdownDataSource
-(NSInteger)numberOfRowsInMainTable:(JGHomeDropdown *)homeDropdown
{
    return self.regions.count;
}

-(NSString *)homeDropdown:(JGHomeDropdown *)homeDropdown titleForRowInMainTable:(NSInteger)row
{
    JGRegion *region = self.regions[row];
    return region.name;
}

-(NSArray *)homeDropdown:(JGHomeDropdown *)homeDropdown subdataForRowInMainTable:(NSInteger)row
{
    JGRegion *region = self.regions[row];
    return region.subregions;
}

#pragma mark - JGHomeDropdownDelegate
-(void)homeDropdown:(JGHomeDropdown *)homeDropdown didSelectRowInMainTable:(NSInteger)row
{
    JGRegion *region = self.regions[row];
    if (region.subregions.count == 0) {
        // 发出通知
        [JGNotificationCenter postNotificationName:JGRegionDidChangeNotification object:nil userInfo:@{JGSelectRegion : region}];
    }
}

-(void)homeDropdown:(JGHomeDropdown *)homeDropdown didSelectRowInSubTable:(NSInteger)subrow inMainTable:(int)mainRow
{
    JGRegion *region = self.regions[mainRow];
    // 发出通知
    [JGNotificationCenter postNotificationName:JGRegionDidChangeNotification object:nil userInfo:@{JGSelectRegion : region, JGSelectSubregionName : region.subregions[subrow]}];
}



@end
